<template>
  <view class="start-index">
	  <!-- <view @click="login">获得信息</view> -->
    <view v-if="tabberPageLoadFlag[0]" :style="{display: currentIndex === 0 ? '' : 'none'}">
      <scroll-view class="custom-tabbar-page" scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
        <home ref="home" @setCurrent="(e)=>setCurrents(e)"></home>
      </scroll-view>
    </view>
    <view v-if="tabberPageLoadFlag[1]" :style="{display: currentIndex === 1 ? '' : 'none'}">
      <scroll-view class="custom-tabbar-page" scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
        <!-- <circle-page ref="circleRef"></circle-page> -->
		<CircleIndex ref="circleRef"></CircleIndex>
      </scroll-view>
    </view>
   <!-- <view v-if="tabberPageLoadFlag[2]" :style="{display: currentIndex === 2 ? '' : 'none'}">
      <scroll-view class="custom-tabbar-page" scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
        <activity ref="activity"></activity>
      </scroll-view>
    </view> -->
    <view v-if="tabberPageLoadFlag[2]" :style="{display: currentIndex === 2 ? '' : 'none'}">
      <scroll-view class="custom-tabbar-page" scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower" style="height: 90vh;">
        <!-- <preferred ref="preferredRef"></preferred> -->
		<createBuil ref="createBuilRef"></createBuil>
      </scroll-view>
    </view>
    <view v-if="tabberPageLoadFlag[3]" :style="{display: currentIndex === 3 ? '' : 'none'}">
      <scroll-view class="custom-tabbar-page" scroll-y enable-back-to-top @scrolltolower="tabbarPageScrollLower">
        <mine ref="mine"></mine>
      </scroll-view>
    </view>
    
    <tn-tabbar
      v-model="currentIndex"
      :list="tabbarList"
      activeColor="#838383"
      inactiveColor="#AAAAAA"
      activeIconColor="#FBBD12"
      :animation="true"
      :safeAreaInsetBottom="true"
      @change="switchTabbar"
    ></tn-tabbar>
  </view>
</template>

<script>
  import Home from './home/home.vue'
  import CirclePage from './circle/circle.vue'
  import CircleIndex from './circle/index.vue'
  import Activity from './activity/activity.vue'
  import Preferred from './preferred/preferred.vue'
  import Mine from './mine/mine.vue'
  import createBuil from './build/build.vue'
  import Tools from '../tools/config.js'
  export default {
    components: {
      Home,
      CirclePage,
	  CircleIndex,
      Activity,
      Preferred,
      Mine,
	  createBuil
    },
    data() {
      return {
        // 底部tabbar菜单数据
        tabbarList: [
          {
            title: '首页',
            activeIcon: '/static/tabbar/home_tnnew.png',
            inactiveIcon: '/static/tabbar/home_tn.png'
          },
          {
            title: '圈子',
            activeIcon: '/static/tabbar/circle_tnnew.png',
            inactiveIcon: '/static/tabbar/circle_tn.png'
          },
          // {
          //   title: '广场',
          //   activeIcon: 'menu-circle',
          //   inactiveIcon: 'rocket',
          //   activeIconColor: '#FFFFFF',
          //   inactiveIconColor: '#FFFFFF',
          //   iconSize: 50,
          //   out: true
          // },
		  {
		    title: '创建圈子',
		    activeIcon: '/static/tabbar/preferred_tnnew.png',
		    inactiveIcon: '/static/tabbar/preferred_tn.png',
		  },
          // {
          //   title: '优选',
          //   activeIcon: '/static/tabbar/preferred_tnnew.png',
          //   inactiveIcon: '/static/tabbar/preferred_tn.png',
          // },
          {
            title: '我的',
            activeIcon: '/static/tabbar/mine_tnnew.png',
            inactiveIcon: '/static/tabbar/mine_tn.png'
          }
        ],
        // tabbar当前被选中的序号
        currentIndex: 0,
        // 自定义底栏对应页面的加载情况
        tabberPageLoadFlag: [],
		islogin:false,
		theloginxx:''
      }
    },
    onLoad(options) {
		 this.getislogin('openid')
		 console.log("2222",options)
      const index = Number(options.index || 0)
      // 根据底部tabbar菜单列表设置对应页面的加载情况
      this.tabberPageLoadFlag = this.tabbarList.map((item, tabbar_index) => {
        return index === tabbar_index
      })
      this.switchTabbar(index)
				//this.getswiperList()
    },
	onShow(){
		console.log("onShow:",this.currentIndex);
		if(this.currentIndex == 1){
			this.$refs.circleRef.initData()
		}else if(this.currentIndex == 0){
			this.$refs.home.initData()
		}
	},
    methods: {
      // 切换导航
      switchTabbar(index) {
        this._switchTabbarPage(index)
        // if (index !== 2) {
        //   this.$refs?.circleRef?.stopAllVideo()
        // }
      },
	  getislogin(key)
	  {
		  let that=this
		  uni.getStorage({
		  	key:key,
			success:function(res){
				console.log('success')
				that.theloginxx=res.data
				// uni.showToast({
				// 	title: 'openid:'+that.theloginxx,
				// 	duration: 2000
				// });
				
				 if(that.theloginxx.length<=0)
				 {
					uni.showModal({
						title:'登录授权',
						content:"是否授权",
						success: () => {
							that.logintest()
						}
					})
				 }
				// uni.showLoading({
				// 	title:'加载中'
				// })
			},fail:function(res){
				uni.showModal({
					title:'登录授权',
					content:"是否授权",
					success: () => {
						that.logintest()
					}
				})
			}
		  })
	  }
	  ,
      setislogin(data)
	  {
		  uni.setStorage({
		  	data:data,
			key:'loginxx',
			success:function(){
				console.log('successs')
			}
		  })
	  },
      
      // 导航页面滚动到底部
      tabbarPageScrollLower(e) {
        // if (this.currentIndex === 3) {
        //   this.$refs.preferredRef.getRandomData && this.$refs.preferredRef.getRandomData()
        // }
      },
      setCurrents(e){
		  this._switchTabbarPage(e.type, e.param)
	  },
      // 切换导航页面
      _switchTabbarPage(index,params = 0) {
        const selectPageFlag = this.tabberPageLoadFlag[index]
        if (selectPageFlag === undefined) {
          return
        }
        if (selectPageFlag === false) {
          this.tabberPageLoadFlag[index] = true
        }
        this.currentIndex = index
		if(index == 1){
			this.$refs.circleRef.tabChange(params)
		}else if(index == 2){
			this.$nextTick(()=>{
				this.$refs.createBuilRef.initData()
			})
		}else if(index == 0){
			this.$refs.home.initData()
		}
      },
	  logintest() {
	  				uni.getUserProfile({
	  					desc: "获取用户基本资料",
	  					lang: 'zh_CN',
	  					success: (user) => {
	  						//获取成功基本资料后开启登录，因为基本资料首先要授权
	  						uni.login({
	  							provider: 'weixin',
	  							success: function(code_res) {
	  								if (code_res.errMsg == "login:ok") {
	  									let code = code_res.code;
	  									console.log(code)
	  									uni.request({
	  										//url: 'http://vote2.tmxxw.com/card.aspx?lx=getunionid&wxcode='+code,
	  										url: Tools.host+'/wshly.ashx',
											method:'POST',
											data:{
												'lx':'userlogin',
												'wxcode':code,
												'tximg':user.userInfo.avatarUrl,
												'nc':user.userInfo.nickName
											},
											success: (session_res) => {
												console.log('session_res：'+session_res.data.data)
												var thejson=JSON.parse(session_res.data.data);
	  											//成功
												uni.setStorageSync("openid",thejson.openid)
												uni.setStorageSync("unionid",thejson.unionid)
												uni.navigateTo({
												      url: '/pages/index'
												    });
												
												// uni.showModal({
												// 	title:'openid：'+thejson.openid,
												// 	showCancel:false
												// })
												//跳转
												// uni.navigateTo({
												// 	url:'/pages/home/home'
												// }) 
	  										},
	  										fail: (res) => {
	  											console.log('登录失败'+res)
												uni.showModal({
													title:'登录失败，请稍后重试',
													showCancel:false
												})
	  										}
	  									});
	  								}
	  								else
	  								{
	  									uni.showModal({
	  										title:'登录失败，请稍后重试',
	  										showCancel:false
	  									})
	  								}
	  							},
	  							fail:(res)=> {
	  								uni.showModal({
	  									title:'登录失败，请稍后重试',
	  									showCancel:false
	  								})
	  							}
	  						});
	  					},
	  					fail: (res) => {
	  						uni.showModal({
	  							title:"用户拒绝授权",
	  							showCancel:false
	  						})
	  					}
	  				});
	  			},
				// 小程序 登录功能
				async loginFn() {
					let that = this;
					let userProfileObject = await that.getUserProfileFn();
					let avatarUrl, nickName, province, city, gender;
				
					if (userProfileObject.type == 'success') {
						avatarUrl = userProfileObject.result.avatarUrl;
						nickName = userProfileObject.result.nickName;
						province = userProfileObject.result.province;
						city = userProfileObject.result.city;
						gender = userProfileObject.result.gender;
					} else {
						uni.showToast({
							icon: 'none',
							title: '获取个人信息失败'
						});
						return false;
					}
				
					uni.login({
						async success(e) {
							console.log('先获取code那堆数据', e);
				
							uni.getUserInfo({
								//获取用户信息
								async success(userInfoRes) {
									let iv = encodeURIComponent(userInfoRes.iv);
									let encryptedData = encodeURIComponent(userInfoRes.encryptedData);
									console.log('uni.getUserInfo 成功的数据', userInfoRes, '\n');
									//第一次提示用户授权 成功后的回调 授权后再点直接成功 拿回来用户信息
				
									console.log('后获取用户信息 包括iv 和 xxxdata字符串', userInfoRes);
				
									let code = e.code;
				
									// 登录时 把分享者的字符串带上
									let sharerObj = {};
									let sharerStr = uni.getStorageSync('sharer'); // 带上分享上级的加密字符串
									if (sharerStr) {
										sharerObj.sharer = sharerStr;
									}
				
									let data = {
										avatar: avatarUrl,
										nickname: nickName,
										area: city,
										sex: gender,
										platform: '小程序',
										code,
										iv,
										encryptedData,
				
										...sharerObj
									};
									let result = await that.$request({
										loading: true,
										url: '/api/login/third',
										data
									});
									console.log('用户登录时带的参数', data, '\n', '返回的结果', result, '\n');
				
									if (result.statusCode == 200) {
										if (result.data.code == 200) {
											that.logOutFn(); // 先退出登录一下
				
											let token = result.data.data.login_token;
											that.$store.commit('setToken', token);
											uni.setStorageSync('token', token);
										
							if (nickName=='微信用户'){
									that.$emit('loginnew');
							}
											uni.hideLoading();
											uni.showLoading({});
											that.hasTokenGetUserInfo(() => {
												uni.hideLoading();
												uni.showToast({
													icon: 'success',
													title: '登录成功'
												});
												
												
												that.$emit('loginSuccessCallback');
												that.closeGlobalLoginFn(false);
											});
										} else {
											uni.showToast({
												icon: 'none',
												title: result.data.msg
											});
										}
									} else {
										uni.showToast({
											icon: 'none',
											title: that.$errorMsg
										});
									}
								},
								fail(e) {
									console.log('登录失败 小程序 getUserInfo 接口fail ', e);
								}
							});
						}
					});
				},
				getswiperList()
				{
						  uni.showModal({
						  	title:'ks22',
						  	content:"ks22",
						  	success: () => {
						  	}
						  });
						  let that=this
						  uni.request({
						  	url: Tools.host+'/wshly.ashx',
						  	method:'POST',
						  	data:{
						  		'lx':'getswiperList',
						  		'openid':''
						  	},
						  	success: (res) => {
						  		//成功
								console.log('res.data：'+res.data.data) 
								uni.showModal({
									title:'ks223',
									content:"ks223"+res.data.data,
									success: () => {
									}
								});
						  		//that.swiperList=res.data.return_msg.data
						  	},
						  	fail: (res) => {
						  		console.log('失败'+res)
								uni.showModal({
									title:'ks223',
									content:"失败"+res,
									success: () => {
									}
								});
						  	}
						  });
				},
    }
  }
</script>

<style lang="scss" scoped>
</style>
